//
//  ConnectViewController.m
//  Light
//
//  Created by 骁唐 on 15/8/27.
//  Copyright (c) 2015年 骁唐. All rights reserved.
//
#import "ConnectViewController.h"
#import "ConnectOffViewController.h"
#import "SCSiriWaveformView.h"
#import "constantDefinition.h"
#import "AppDelegate.h"
#import "ConnectOnViewController.h"
#import "SetViewController.h"
#import "UserConfig.h"
#import "HomeTwoViewController.h"
#import "SliderViewController.h"
#import "BluetoothController.h"
#import "PeriperalInfo.h"

@interface ConnectViewController ()<UIApplicationDelegate,UIGestureRecognizerDelegate,BTServerDelegate,UIAlertViewDelegate>
// 中央管理者
@property(nonatomic,strong)CBCentralManager *mgr;
//外设数组
@property(nonatomic,strong)NSMutableArray *peripherals;
//外设数组名字
@property(nonatomic,strong)NSMutableArray *peripheralsName;
//12位key截取判断
@property (assign,nonatomic) BOOL keyMark;
//报告大于一条 存储进入判断
@property(assign,nonatomic) BOOL report;
//报告可变数组
@property (strong,nonatomic) NSMutableData *reportData;
//背景图片
@property (weak, nonatomic) IBOutlet UIImageView *backGround;
//跳过view
@property (weak, nonatomic) IBOutlet UIView *loginGotoView;
//跳过mark标记
@property (assign,nonatomic) BOOL loginGotoMark;
//返回button
@property (weak, nonatomic) IBOutlet UIButton * buttonBack;
//返回图标
@property (weak, nonatomic) IBOutlet UIButton * buttonBackMark;

//曲线动画
@property (nonatomic, weak) IBOutlet SCSiriWaveformView *waveformView;
@property (nonatomic, weak) IBOutlet SCSiriWaveformView *wave2;
@property (weak, nonatomic) IBOutlet SCSiriWaveformView *wave3;
//正在搜索设备 标签
@property (weak, nonatomic) IBOutlet UILabel *searchLabel;
@property (strong,nonatomic) NSTimer *offTimer;
@property (strong,nonatomic)BluetoothController *defaultBTServer;
@property (strong,nonatomic)PeriperalInfo * currentperih;

//
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *viewPictureWidth;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *viewPictureHeight;
@end

@implementation ConnectViewController
{
    NSTimer *writeCurrentTime;
    NSTimer *connectNewPeripheralsTime;
    BOOL judgeConnectNew;
    int peripheralIndex;//连接到数组中的第几个设备
    int peripheralOFF;//标记3S鈡扫描的个数
    int connect_times;
    BOOL isGO;//如果接收到aaee0160aa,需要跳过。
    BOOL isShowAlertViewOfUpadateHardWare;//标记是否显示过 硬件升级的标记变量。防止多次弹窗。
}

#pragma mark -
#pragma mark 页面即将显示时
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
        //强制竖屏
    [[UIDevice currentDevice] setValue:[NSNumber numberWithInteger:
                                        UIInterfaceOrientationPortrait]  forKey:@"orientation"];
    //4s 约束
    if (SCREEN_HEIGHT < 569)
    {//宽度为320 的屏幕
        self.viewPictureWidth.constant = 200;
        self.viewPictureHeight.constant = 200;
    }
    else
    {
        self.viewPictureWidth.constant = 274;
        self.viewPictureHeight.constant = 274;
    }
    
    long long int currentTimeInt = [TJJDefines getTimeIntSince1970Current];
    if (currentTimeInt>=16200&& currentTimeInt <=34200) {
        self.backGround.image = [UIImage imageNamed:@"backgroundOne"];
    }else if (currentTimeInt>34200 && currentTimeInt<=55800)
    {
        self.backGround.image = [UIImage imageNamed:@"backgroundTwo"];
    }else if (currentTimeInt>55800 && currentTimeInt<=70200)
    {
        self.backGround.image = [UIImage imageNamed:@"backgroundThree"];
    }else if(currentTimeInt >70200 || currentTimeInt<16200)
    {
        self.backGround.image = [UIImage imageNamed:@"background_night"];
    }
    
    self.defaultBTServer = [BluetoothController defaultBTServer];
    self.defaultBTServer.delegate = (id)self;
    AppDelegate *delegate = [[UIApplication sharedApplication]delegate];
    delegate.fromwhere = @"Connect";
    [self.defaultBTServer startScan];//调用服务方法中的开始搜索方法
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    self.navigationController.interactivePopGestureRecognizer.delegate = self;
    [[NSNotificationCenter defaultCenter] postNotificationName:TIMER_REMOVER object:nil userInfo:nil];//关闭首页定时器通知
    _searchLabel.textColor = APPCOLOUR;//设置搜索提示文字颜色
    [self animation];//设置动画
    self.keyMark = YES;//12位key值判断（没明白）
    self.peripherals = [[NSMutableArray alloc] init];
    peripheralIndex = 0;//标记计数初始为0
    peripheralOFF = 0;//初始化统计个数为0
    self.reportData = [[NSMutableData alloc] init];//睡眠报告数组
    connect_times = 0;
    AppDelegate * delegate = [[UIApplication sharedApplication] delegate];
    if (self.mark == YES)
    {//从设置界面进入的
        self.loginGotoView.hidden = YES;//跳过按钮隐藏
        delegate.markGo = @"setting";//标记绑定界面 从设置界面进入
    }
    else
    {
        delegate.markGo = @"landing";//标记绑定界面 是注册进来的
        self.buttonBack.hidden = YES;//隐藏返回按钮
        self.buttonBackMark.hidden = YES;
    }
    isShowAlertViewOfUpadateHardWare = NO;//初始化 硬件升级为NO
}

#pragma mark -
#pragma mark 页面消失，进入后台不显示该页面，关闭定时器
-(void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    self.keyMark = NO;//12bit判断关闭
    AppDelegate *delegate = [[UIApplication sharedApplication]delegate];
    self.defaultBTServer.delegate = delegate.homepageid;   //恢复homepage委托方法
    delegate.fromwhere = @"Home";
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    return  NO;
}

#pragma mark -
#pragma mark 中心设备扫描发现设备回调
-(void)didFoundPeripheral
{
    return ;
}

#pragma mark -
#pragma mark  停止扫描
-(void)didStopScan
{
    [self.peripherals removeAllObjects];
    for (int i=0;i<self.defaultBTServer.discoveredPeripherals.count;i++)
    {
        [self.peripherals addObject:self.defaultBTServer.discoveredPeripherals[i]];
//        PeriperalInfo * pi =self.defaultBTServer.discoveredPeripherals[i];
        //TJJLog("RSSI排序：%@",pi.RSSI);
    }
    AppDelegate *delegate = [[UIApplication sharedApplication]delegate];
    delegate.searchcancel = NO;
    [self performSelectorInBackground:@selector(judgeConnectPeripheral) withObject:nil];
    
//    [self judgeConnectPeripheral];//改成这个了
    
}

#pragma mark -
#pragma mark 开始连接设备
-(void)judgeConnectPeripheral
{
    AppDelegate *delegate = [[UIApplication sharedApplication]delegate];
    if (self.loginGotoMark != YES)
    {
        if(self.peripherals.count > 0)
        {
            int i=0;
            for (i=0;i<self.peripherals.count;i++)
            {//新加一个变量
                isGO = NO;//新加了一个标记变量
                AppDelegate *delegate = [[UIApplication sharedApplication]delegate];
                connect_times = 0;
                if (![TJJDefines isNull:self.peripherals[i]])
                {
                    self.currentperih = self.peripherals[i];
                    [self.defaultBTServer connect:self.currentperih];
                    UserConfig *config = [UserConfig sharingUserConfig];
                    [config setBluetoothAddress:self.currentperih.uuid];//保存 存储UUID
                    TJJLog(@"尝试绑定第%d个设备,UUID:%@",i,self.currentperih.uuid);
                }
                while (self.defaultBTServer.selectPeripheral.state!= CBPeripheralStateConnected && connect_times<5) ;
//                [NSThread sleepForTimeInterval:3];  //等3秒时间，没回复连下一个。
                for(int i=0;i<50;i++)
                {
                    if (isGO) break;
                    [NSThread sleepForTimeInterval:0.1];  //等3秒时间，没回复连下一个。
                }
                if (delegate.searchcancel)
                {   //用户点了返回了
                    if (self.defaultBTServer.selectPeripheral != nil)
                        [self.defaultBTServer disConnect];
                    return ;
                }
                if (delegate.Bluetooth == YES) {
                    TJJLog(@"绑定第%d个设备成功",i);
                    break;
                }
                else
                {
                    TJJLog(@"绑定第%d个设备失败，尝试下一个设备",i);
                }
            }
            if (delegate.Bluetooth != YES)
            {
                TJJLog(@"所有设备连接失败");
                dispatch_async(dispatch_get_main_queue(), ^{//主线程  刷新UI
                [self performSegueWithIdentifier:@"ConnectToOff" sender:self];  //跳转到失败界面
                });
            }
        }
        else
            dispatch_async(dispatch_get_main_queue(), ^{//主线程  刷新UI
                [self performSegueWithIdentifier:@"ConnectToOff" sender:self];  //跳转到失败界面
            });
    }
}

#pragma mark -
#pragma mark 设备特征值已经获得了
-(void)didDiscoverCharacteristic
{
    AppDelegate * delegate = [[UIApplication sharedApplication] delegate];
    delegate.writeCharacteristic  = self.defaultBTServer.txCharacteristic;
    delegate.peripheral = self.defaultBTServer.selectPeripheral;//设置全局 peripheral
    delegate.readCharacteristic = self.defaultBTServer.rxCharacteristic;//设置全局 readCharacteristic
    [self writeOne];//写入 NO key pair ae0101aa
}
#pragma mark -
#pragma mark 判断链接标志
- (void)judgeAskConnectMark
{
    judgeConnectNew = YES;
}
#pragma mark -
#pragma mark 发现外设
-(void)didDisconnectFromPeriph
{
    if (connect_times<5)
    {
        [self.defaultBTServer connect:self.currentperih];
        connect_times ++ ;
    }
    TJJLog(@"外设在绑定设备界面断开连接重连%d次",connect_times); //在绑定设备界面断开连接，不需要重连
    return ;
}

#pragma mark -
#pragma mark 外设特征值（读取信息）
- (void)didReadvalue
{
    //用作报告判断真头data
    AppDelegate *delegate = [[UIApplication sharedApplication] delegate];
    NSData * incomedate = [delegate.readCharacteristic value];
    Byte * data2byte = (Byte *)[incomedate bytes];
    const uint8_t * dat = delegate.readCharacteristic.value.bytes;
    NSMutableString * mutableString = [[NSMutableString alloc] initWithCapacity:0];
    for (int i = 0; i < delegate.readCharacteristic.value.length; i++)
    {
        [mutableString appendString:[NSString stringWithFormat:@"%02x",dat[i]]];
    }
    //需要先转成string，之前demo都是判断以string的形式判断的。
    NSString * string = mutableString;
    //        if ([string isEqualToString:@"43"])//C
    if ([string isEqualToString:@"43"] || [string isEqualToString:@"1818"] || [string isEqualToString:@"4343"])//C
    {
        if (!isShowAlertViewOfUpadateHardWare)
        {//如果弹出提示框了
            delegate.Bluetooth = YES;
            delegate.judgeMyConnect = YES;//连接成功
            delegate.myRemoveConnect = NO;
            UserConfig *config = [UserConfig sharingUserConfig];
            [config setConnectCool:@"1"];
            [self.defaultBTServer stopScan:YES];//停止扫描外设
            isShowAlertViewOfUpadateHardWare = YES;//改变标记
            UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"眼罩正在升级状态，请立即完成升级状态" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
            alertView.tag = 991;
            [alertView show];
        }
        
        NSLog(@"收到了43 43 43 43");
        return; //退出以下的，需要进行断开连接操作
    }
    
    
    if (incomedate.length == 20)
    {
        int i=0;
        for (i =0;i<incomedate.length; i++)
        {
            if (data2byte[i] != 0x00) break;
        }
        if (i==20)
            return ;
        if (data2byte[0]==0xAA && data2byte[10]==0xAA && !delegate.isAtHeart)
        {
            TJJLog(@"波形未关闭，发送关闭指令");
            Byte ACkValue[4] = {0};
            ACkValue[0] = 0xAE; ACkValue[1] = 0x01; ACkValue[2] = 0x06; ACkValue[3] = 0xAA;
            NSData *data = [NSData dataWithBytes:&ACkValue length:sizeof(ACkValue)];
            [delegate.peripheral writeValue:data forCharacteristic:delegate.writeCharacteristic type:CBCharacteristicWriteWithResponse];
            AppDelegate *delegate = [[UIApplication sharedApplication] delegate];
            [self currentPowerConnect];
            TJJLog(@"当前连接的设备%@",delegate.peripheral);
            delegate.Bluetooth = YES;
            delegate.judgeMyConnect = YES;//连接成功
            delegate.myRemoveConnect = NO;
            UserConfig *config = [UserConfig sharingUserConfig];
            [config setConnectCool:@"1"];
            //[self performSelector:@selector(currentTimeWay) withObject:nil afterDelay:0];//延迟写入时间
            [self performSelector:@selector(readHardInfo) withObject:nil afterDelay:0.5];//延迟读取硬件信息
            [self performSelector:@selector(readSerialNumber) withObject:nil afterDelay:1];//延迟读取硬件序列号信息
            [self performSegueWithIdentifier:@"ConnectToOn" sender:self];//跳转到设备连接成功界面
            [[NSNotificationCenter defaultCenter] postNotificationName:@"userHead" object:nil userInfo:nil];//红色头像图标通知
            return ;
        }
    }
    
    TJJLog(@"%lu",(unsigned long)delegate.readCharacteristic.value.length);
    TJJLog(@"%@",delegate.readCharacteristic.value);
    if(incomedate.length== 5)
    {
        //返回判断截取一个字节，判断配对成功
        if (data2byte[3] == 0x06)
        {
            AppDelegate *delegate = [[UIApplication sharedApplication] delegate];
            [self currentPowerConnect];//电量状态请求
            TJJLog(@"当前连接的设备%@",delegate.peripheral);
            delegate.Bluetooth = YES;
            delegate.judgeMyConnect = YES;//连接成功
            delegate.myRemoveConnect = NO;
            UserConfig *config = [UserConfig sharingUserConfig];
            [config setConnectCool:@"1"];
            //[self performSelector:@selector(currentTimeWay) withObject:nil afterDelay:0];//延迟写入时间
            [self performSelector:@selector(readHardInfo) withObject:nil afterDelay:0.5];//延迟读取硬件信息
            [self performSelector:@selector(readSerialNumber) withObject:nil afterDelay:1.0];//延迟读取硬件序列号信息
            [self performSegueWithIdentifier:@"ConnectToOn" sender:self];//跳转到设备连接成功界面
            [[NSNotificationCenter defaultCenter] postNotificationName:@"userHead" object:nil userInfo:nil];//红色头像图标通知
        }
        else if (data2byte[3] == 0x60)
        {//没有电量
            isGO = YES;
        }
        
    }
    else if(incomedate.length == 10)
    {
        AppDelegate *delegate = [[UIApplication sharedApplication] delegate];
        if (!delegate.Bluetooth)
        {//如果是非绑定状态
            NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithCapacity:0];
            if (data2byte[0]==0xAA && data2byte[1]==0xEE && data2byte[2]==0x01 && data2byte[3]==0x06)
            {
                //这里直接就配对成功了，在这个界面不可能接收报告的，所以直接返回成功
                delegate.Bluetooth = YES;
                delegate.judgeMyConnect = YES;
                delegate.myRemoveConnect = NO;
                //[self performSelector:@selector(currentTimeWay) withObject:nil afterDelay:0];
                [self performSelector:@selector(readHardInfo) withObject:nil afterDelay:0];//延迟读取硬件信息
                [self performSelector:@selector(readSerialNumber) withObject:nil afterDelay:0.6];//延迟读取硬件序列号信息
                if (data2byte[8] ==0x41)
                {
                    TJJLog(@"YES41配对成功");
                    TJJLog(@"当前连接的设备%@",delegate.peripheral);
                    //充电中
                    [dict setObject:@"6" forKey:@"keyCharge"];
                }
                if (data2byte[8] == 0x42)
                {
                    TJJLog(@"YES42配对成功");
                    TJJLog(@"当前连接的设备%@",delegate.peripheral);
                    //充电完成
                    [dict setObject:@"7" forKey:@"keyComplete"];
                }
                UserConfig *config = [UserConfig sharingUserConfig];
                [config setConnectCool:@"1"];
                //发送电量改变的通知
                [[NSNotificationCenter defaultCenter] postNotificationName:@"power" object:nil userInfo:dict];
                // userhead有问题
                [[NSNotificationCenter defaultCenter] postNotificationName:@"userHead" object:nil userInfo:dict];
                [self performSegueWithIdentifier:@"ConnectToOn" sender:self];//跳转到设备连接成功界面
            }
        }
    }
    else
    {
        if (incomedate.length == 12)
        {
            if (data2byte[0]==0xAA && data2byte[1]==0xEE && data2byte[2]==0x08 && data2byte[11]==0xAA) {  //key值
                TJJLog(@"data%@",incomedate);
                [self writeTwoValue:data2byte];
            }
            if (data2byte[0]==0xAA && data2byte[1]==0xBB && data2byte[2]==0x08 && data2byte[11]==0xAA) {
                TJJLog(@"序列号%@",incomedate);
                NSMutableString * mutableString = [[NSMutableString alloc] initWithCapacity:0];
                for (int i = 0; i < incomedate.length; i++)
                {
                    [mutableString appendString:[NSString stringWithFormat:@"%02x",data2byte[i]]];
                }
                UserConfig * config = [UserConfig sharingUserConfig];
                [config setSerialNumber:[mutableString substringWithRange:NSMakeRange(6, 16)]];//保存序列号
            }
        }
    }
//    char instr[100];
//    memcpy(instr,data2byte,incomedate.length);
//    instr[incomedate.length] = 0x00;
//    char* loc = strstr(instr,"VER");
//    if (loc!=NULL)
//    {
//        NSString * datastring = [[NSString alloc]initWithData:incomedate encoding:NSUTF8StringEncoding];
//        UserConfig * config = [UserConfig sharingUserConfig];
//        [config setHardware:datastring];//保存固件版本
//        NSArray * array = [datastring componentsSeparatedByString:@"_VER"];
//        NSString *Old_Version = [array lastObject];// 固件版本版本  如1.2
//        CGFloat ver = [Old_Version floatValue];
//        if (ver >= 1.4)
//        {
//            [config setMarkNewNoSendKey:YES];//设置 标记1.4 以上为YES
//        }
//        else
//        {
//            [config setMarkNewNoSendKey:NO];//设置标记 1.4 以下的为NO
//        }
//        TJJLog(@"00000000000000用户注册 然后进入的绑定界面 需要添加标记变量  标记需要延迟推送");
//        delegate.isUpdateHardWare = YES;//标记现在在进行眼罩升级
//        //TODO:固件升级  需要判断是否是初次使用，如果初次使用，需要先跳转，然后才能进行升级。这边需要用到已经定义好的一个标记，或者单独做一个标记。
//        if (self.mark == YES || [delegate.markGo isEqualToString:@"setting"])
//        {//从设置界面进入的
//        //发送通知 进入主界面，进行判断是否升级的。
//            [[NSNotificationCenter defaultCenter] postNotificationName:@"checkUpdateConnectHome" object:nil];
//            TJJLog(@"111111111111用户注册 然后进入的绑定界面 需要添加标记变量  标记需要延迟推送");
//        }
//        else if (self.mark == NO || [delegate.markGo isEqualToString:@"landing"])
//        {//用户注册 然后进入的绑定界面 需要添加标记变量  标记需要延迟HOME界面进行判断
//            delegate.markIsgetHardNumber = YES;
//            TJJLog(@"2222222222222用户注册 然后进入的绑定界面 需要添加标记变量  标记需要延迟推送");
//        }
//    }
    //蓝牙固件版本 和  蓝牙适配器版本
    NSString * stringData = [[NSString alloc] initWithData:incomedate encoding:NSUTF8StringEncoding];
    TJJLog(@"ConnectView——字符串打印:%@",stringData);
    NSRange range = [stringData rangeOfString:@"VER"];
    if (range.length == 3)
    {
        UserConfig * config = [UserConfig sharingUserConfig];
        NSArray * tempArray = [stringData componentsSeparatedByString:@"."];
        NSArray * tempArray_ = [stringData componentsSeparatedByString:@"_"];
        if (tempArray.count == 2)
        {
            if (tempArray_.count == 2)
            {
                TJJLog(@"SXW__保存固件版本:%@",stringData);
                [config setHardware:stringData];//保存固件版本
                NSArray * array = [stringData componentsSeparatedByString:@"_VER"];
                NSString *Old_Version = [array lastObject];// 固件版本版本  如1.2
                CGFloat ver = [Old_Version floatValue];
                if (ver >= 1.4)
                {
                    [config setMarkNewNoSendKey:YES];//设置 标记1.4 以上为YES
                }
                else
                {
                    [config setMarkNewNoSendKey:NO];//设置标记 1.4 以下的为NO
                }
                TJJLog(@"00000000000000用户注册 然后进入的绑定界面 需要添加标记变量  标记需要延迟推送");
                delegate.isUpdateHardWare = YES;//标记现在在进行眼罩升级
                //TODO:固件升级  需要判断是否是初次使用，如果初次使用，需要先跳转，然后才能进行升级。这边需要用到已经定义好的一个标记，或者单独做一个标记。
                if (self.mark == YES || [delegate.markGo isEqualToString:@"setting"])
                {//从设置界面进入的
                //发送通知 进入主界面，进行判断是否升级的。
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"checkUpdateConnectHome" object:nil];
                    TJJLog(@"111111111111用户注册 然后进入的绑定界面 需要添加标记变量  标记需要延迟推送");
                }
                else if (self.mark == NO || [delegate.markGo isEqualToString:@"landing"])
                {//用户注册 然后进入的绑定界面 需要添加标记变量  标记需要延迟HOME界面进行判断
                    delegate.markIsgetHardNumber = YES;
                    TJJLog(@"2222222222222用户注册 然后进入的绑定界面 需要添加标记变量  标记需要延迟推送");
                }
            }
            else
            {//蓝牙版本号
                //需要从VER的V开始取
                NSString * stringTemp = [stringData substringFromIndex:range.location];
                TJJLog(@"SXW__蓝牙适配器版本:%@",stringTemp);
                [config setBLEHardware:stringTemp];//保存蓝牙适配器版本
            }
        }
    }
}

#pragma mark -
#pragma mark - 写入 NO key pair ae0101aa
- (void)writeOne
{
    AppDelegate *delegate = [[UIApplication sharedApplication] delegate];
    //第一次写入
    TJJLog(@"ConnectViewController 第一次写入 NO key peir ae0101aa");
    NSData * data = [TJJ_SD_BLE_INSTRUCTIONS writeString:SD_SEND_NOKEYJOINT];
    [delegate.peripheral writeValue:data forCharacteristic:delegate.writeCharacteristic type:CBCharacteristicWriteWithResponse];
}

#pragma mark -
#pragma mark - Had key pair ae0902*****aa 第二次写入
-(void)writeTwoValue:(Byte *)data
{
    AppDelegate *delegate = [[UIApplication sharedApplication] delegate];
    Byte key_Value[12];
    memcpy(key_Value, data, 12);
    key_Value[0] = 0xAE; key_Value[1] = 0x09; key_Value[2] = 0x02;
    //SXW__保存key，把key存入本地
    UserConfig *userConfig = [UserConfig sharingUserConfig];
    NSData *writekey = [[NSData alloc] initWithBytes:key_Value length:12];
    NSMutableData * w_k = [[NSMutableData alloc] initWithData:writekey];
    [userConfig setBlueToothKey:w_k];
    [delegate.peripheral writeValue:writekey
              forCharacteristic:delegate.writeCharacteristic
                           type:CBCharacteristicWriteWithResponse];
    TJJLog(@"ConnectViewController 第二次写入 Had key peir %@",writekey);
}

#pragma mark - 模式开启关闭
#pragma mark - 页面传值
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:@"ConnectToOn"]) {
        ConnectOnViewController *__weak connectOn = [segue destinationViewController];
        connectOn.mark = _mark;
    }
    if ([segue.identifier isEqualToString:@"ConnectToOff"]) {
        ConnectOffViewController *__weak connectOff = [segue destinationViewController];
        connectOff.OffMark = _mark;
    }
}

#pragma mark -
#pragma mark 返回
- (IBAction)backClick {
//    [[NSNotificationCenter defaultCenter] postNotificationName:TIMER_ADD object:nil userInfo:nil];//开启首页定时器通知
    AppDelegate *delegate = [[UIApplication sharedApplication]delegate];
    delegate.searchcancel = YES;
    [self.defaultBTServer stopScan:YES];//停止扫描外设
    if (self.defaultBTServer.selectPeripheral != nil) {
        [self.defaultBTServer disConnect];
    }
    [self.navigationController popViewControllerAnimated:YES];
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark -
#pragma mark 电量状态请求
-(void)currentPowerConnect
{
    AppDelegate *delegate = [[UIApplication sharedApplication]delegate];
    Byte ACkValue[4] = {0};
    ACkValue[0] = 0xAE; ACkValue[1] = 0x01; ACkValue[2] = 0x24; ACkValue[3] = 0xAA;
    NSData *data = [NSData dataWithBytes:&ACkValue length:sizeof(ACkValue)];
    [delegate.peripheral writeValue:data
              forCharacteristic:delegate.writeCharacteristic
                           type:CBCharacteristicWriteWithResponse];
    TJJLog(@"电量请求");
}

#pragma mark -
#pragma mark 读取硬件版本信息指令
- (void)readHardInfo
{
    [TJJ_SD_BLE_INSTRUCTIONS readHardInfo];//读取硬件信息
}

#pragma mark -
#pragma mark 读取硬件序列号信息指令
- (void)readSerialNumber
{
    AppDelegate *delegate = [[UIApplication sharedApplication]delegate];
    Byte ACkValue[4] = {0};
    ACkValue[0] = 0xAE; ACkValue[1] = 0x01; ACkValue[2] = 0x53; ACkValue[3] = 0xAA;
    NSData *data = [NSData dataWithBytes:&ACkValue length:sizeof(ACkValue)];
    [delegate.peripheral writeValue:data
              forCharacteristic:delegate.writeCharacteristic
                           type:CBCharacteristicWriteWithResponse];
    TJJLog(@"序列号请求");
}

#pragma mark 跳过按钮
- (IBAction)gotoClick:(UIButton *)sender {
    self.loginGotoMark = YES;
    //TODO:下面一行反正没作用，直接屏蔽了。
//    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(judgeConnect) object:nil];//可以取消成功   判断是否连接成功
    AppDelegate *delegate = [[UIApplication sharedApplication]delegate];
    delegate.searchcancel = YES;
    [self.defaultBTServer stopScan:YES];//停止扫描外设
    if (self.defaultBTServer.selectPeripheral != nil) {
        [self.defaultBTServer disConnect];//中断连接
    }
    BOOL HaveRoot = NO;//标记是否有Root
    for (UIViewController * controller in self.navigationController.viewControllers)
    {
        if ([controller isKindOfClass:[SliderViewController class]])
        {//如果是rootView
            HaveRoot = YES;
            [self.navigationController popToViewController:controller animated:YES];
        }
    }
    if (!HaveRoot)
    {
        HomeTwoViewController *homet = [[HomeTwoViewController alloc] init];
        self.defaultBTServer.delegate = homet;
        SliderViewController *slider = [SliderViewController sharedSliderController];
        if (SCREEN_WIDTH > 320)
        {//6以及以上的尺寸
            slider.LeftSContentOffset =  SCREEN_WIDTH-WIDTH_MAIN_6*SCREEN_SCALE;//SXW__设置侧边栏
        }
        else
        {//6以下的尺寸
            slider.LeftSContentOffset =  SCREEN_WIDTH-WIDTH_MAIN*SCREEN_SCALE;//SXW__设置侧边栏
        }
        slider.LeftSContentScale = 1;//左视图缩小，1表示不缩小。
        UIStoryboard *userSt = [UIStoryboard storyboardWithName:@"User" bundle:nil];
        slider.LeftVC = [userSt instantiateViewControllerWithIdentifier:@"userViewId"];
        slider.MainVC = homet;
        UINavigationController *navigationVc = [[UINavigationController alloc]initWithRootViewController:slider];
        navigationVc.navigationBar.hidden = YES;
        delegate.window.rootViewController = navigationVc;
    }
}

#pragma mark -
#pragma mark 动画
- (void)animation
{
    CADisplayLink *displaylink = [CADisplayLink displayLinkWithTarget:self selector:@selector(updateMeters)];
    [displaylink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
    [self.waveformView setWaveColor:[UIColor whiteColor]];
    [self.waveformView setPrimaryWaveLineWidth:1.5f];
    [self.waveformView setSecondaryWaveLineWidth:1.0f];
    [self.wave2 setWaveColor:[UIColor colorWithRed:124.0/255.0 green:208.0/255.0 blue:20.0/255.0 alpha:1.0]];
    [self.wave2 setPrimaryWaveLineWidth:1.5f];
    [self.wave2 setSecondaryWaveLineWidth:1.0];
    [self.wave2 setPhaseShift:0.08f];
    [self.wave2 setFrequency:1.5f];
    [self.wave3 setWaveColor:[UIColor colorWithRed:37.0/255.0 green:180.0/255.0 blue:161.0/255.0 alpha:1.0]];
    [self.wave3 setPrimaryWaveLineWidth:1.5f];
    [self.wave3 setSecondaryWaveLineWidth:1.0];
    [self.wave3 setPhaseShift:-0.08f];
    [self.wave3 setFrequency:1.0f];
}

#pragma mark -
#pragma mark 更新动画线条函数
- (void)updateMeters
{
    CGFloat normalizedValue = pow (0.5, 0.9);
    CGFloat wave2lizedValue = pow(0.5, 0.9);
    CGFloat wave3lizeValue = pow(0.2, 1.0);
    [self.waveformView updateWithLevel:normalizedValue];
    [self.wave2 updateWithLevel:wave2lizedValue];
    [self.wave3 updateWithLevel:wave3lizeValue];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (alertView.tag)
    {
        case 991:
        {//用户正在进行眼罩升级  TODO:固件升级
            //如果RootViewController是 Home
            BOOL HaveRoot = NO;//标记是否有Root
            for (UIViewController * controller in self.navigationController.viewControllers)
            {
                if ([controller isKindOfClass:[SliderViewController class]])
                {//如果是rootView
                    HaveRoot = YES;
//                    [self.navigationController popToViewController:controller animated:YES];
                    AppDelegate *delegate = [[UIApplication sharedApplication]delegate];
                    delegate.isUpdateHardWare = YES;//标记现在在进行眼罩升级
                    [self.navigationController popToRootViewControllerAnimated:YES];
                    //发送通知 进入主界面，进行判断是否升级的。
                    NSNotification *notification =[NSNotification notificationWithName:@"checkUpdateConnect" object:nil userInfo:nil];
                    [[NSNotificationCenter defaultCenter] postNotification:notification];
                }
            }
            if (!HaveRoot)
            {//如果是初次安装并且升级界面检测到43 的
                AppDelegate *delegate = [[UIApplication sharedApplication]delegate];
//                delegate.isUpdateHardWare = YES;//标记现在在进行眼罩升级
                delegate.markIsgetHardNumber = YES;
                
                HomeTwoViewController *homet = [[HomeTwoViewController alloc] init];
                self.defaultBTServer.delegate = homet;
                SliderViewController *slider = [SliderViewController sharedSliderController];
                if (SCREEN_WIDTH > 320)
                {//6以及以上的尺寸
                    slider.LeftSContentOffset =  SCREEN_WIDTH-WIDTH_MAIN_6*SCREEN_SCALE;//SXW__设置侧边栏
                }
                else
                {//6以下的尺寸
                    slider.LeftSContentOffset =  SCREEN_WIDTH-WIDTH_MAIN*SCREEN_SCALE;//SXW__设置侧边栏
                }
                slider.LeftSContentScale = 1;//左视图缩小，1表示不缩小。
                UIStoryboard *userSt = [UIStoryboard storyboardWithName:@"User" bundle:nil];
                slider.LeftVC = [userSt instantiateViewControllerWithIdentifier:@"userViewId"];
                slider.MainVC = homet;
                UINavigationController *navigationVc = [[UINavigationController alloc]initWithRootViewController:slider];
                navigationVc.navigationBar.hidden = YES;
                delegate.window.rootViewController = navigationVc;
            }
        }
        break;
        
        default:
        break;
    }
}

@end
